package cj.web.lkg.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.web.constants.AppUserInfoStateEnum;
import cj.web.lkg.dao.AnswersDAO;
import cj.web.lkg.dao.AppUserDAO;
import cj.web.lkg.dao.ConfigDAO;
import cj.web.login.controllers.BaseController;

@Path("/answers")
public class AnswersController extends BaseController{

	private static Logger logger = Logger.getLogger(AnswersController.class.getName());
	
	@Autowired
	private AnswersDAO answersDao;
	@Autowired
	private AppUserDAO appuserDao;
	@Autowired
	private ConfigDAO configDao;
	
	/**
	 * 提交问答
	 * @param devicesId
	 * @param title
	 * @param msgs
	 * @return
	 */
	@Post("createQue")
	public String createQue(@Param("devicesId") String devicesId,@Param("title") String title,
			@Param("msgs") String msgs,@Param("carouselImage") String carouselImage)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> apuser = appuserDao.queryAppUserByDevicesId(devicesId);
		if(apuser.size()>0)
		{
			boolean flag = returnWordFlag(msgs);
			if(flag){
				//true
				//禁言
				jo.put("appUserInfoState", AppUserInfoStateEnum.MG.getValue());
				jo.put("returnMsg", "您提问中包含敏感词!");
				return "@"+jo.toString();
			}
			
			int state = Integer.parseInt(apuser.get(0).get("state").toString());
			int userId = Integer.parseInt(apuser.get(0).get("id").toString());
			
			if(AppUserInfoStateEnum.JY.getValue()==state)
			{
				//禁言
				jo.put("appUserInfoState", AppUserInfoStateEnum.JY.getValue());
				jo.put("returnMsg", "您已被禁言!");
			}
			else
			{
				jo.put("appUserInfoState", AppUserInfoStateEnum.ZC.getValue());
				
				Map rep = new HashMap();
				rep.put("title", title);
				rep.put("msg", msgs);
				rep.put("createUser", userId);
				rep.put("userId", userId);
				rep.put("carouselImage", carouselImage);
				answersDao.createQue(rep);
			}
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 回答问题
	 * @param devicesId
	 * @param msgs
	 * @return
	 */
	@Get("createAns")
	public String createAns(@Param("devicesId") String devicesId,@Param("feedbackId") int feedbackId,
			@Param("reply") String reply,@Param("isAnonymous") int isAnonymous)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> apuser = appuserDao.queryAppUserByDevicesId(devicesId);
		if(apuser.size()>0)
		{
			boolean flag = returnWordFlag(reply);
			if(flag){
				//true
				//禁言
				jo.put("appUserInfoState", AppUserInfoStateEnum.MG.getValue());
				jo.put("returnMsg", "您回答中包含敏感词!");
				return "@"+jo.toString();
			}
			
			int state = Integer.parseInt(apuser.get(0).get("state").toString());
			
			if(AppUserInfoStateEnum.JY.getValue()==state)
			{
				//禁言
				jo.put("appUserInfoState", AppUserInfoStateEnum.JY.getValue());
				jo.put("returnMsg", "您已被禁言!");
			}
			else
			{
				jo.put("appUserInfoState", AppUserInfoStateEnum.ZC.getValue());
				
				List<Map> quels = answersDao.queryDetailById(feedbackId);
				
				if(quels.size()>0)
				{
					//提问用户ID
					int userId = Integer.parseInt(quels.get(0).get("userId").toString());
					//提问内容
					String contents = quels.get(0).get("msg").toString();
					//回复用户ID
					int replyUserId = Integer.parseInt(apuser.get(0).get("id").toString());
					//回复用户名称
					String replyName =apuser.get(0).get("name")==null?"":apuser.get(0).get("name").toString();
					
					Map rep = new HashMap();
					
					rep.put("feedbackId", feedbackId);
					rep.put("userId", userId);
					rep.put("contents", contents);
					rep.put("isAnonymous", isAnonymous);
					rep.put("reply", reply);
					rep.put("replyUserId", replyUserId);
					rep.put("replyName", replyName);
					rep.put("createUser", replyUserId);
					
					answersDao.createAns(rep);
				}
				
			}
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 点赞回答
	 * @param devicesId
	 * @param feedbackId
	 * @return
	 */
	@Get("createAnsPraise")
	public String createAnsPraise(@Param("devicesId") String devicesId,@Param("feedbackId") int feedbackId,@Param("feedbackReplyId") int feedbackReplyId)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> apuser = appuserDao.queryAppUserByDevicesId(devicesId);
		if(apuser.size()>0)
		{
			String createUser = apuser.get(0).get("name")==null?apuser.get(0).get("id").toString():apuser.get(0).get("name").toString();
			int userId = Integer.parseInt(apuser.get(0).get("id").toString());
			
			int size = answersDao.queryAnsPraiseSize(feedbackId,feedbackReplyId, userId);
			
			if(size==0)
				//没有点赞记录
			{
				Map rep = new HashMap();
				
				rep.put("feedbackId", feedbackId);
				rep.put("feedbackReplyId", feedbackReplyId);
				rep.put("userId", userId);
				rep.put("userName", createUser);
				rep.put("createUser", userId);
				rep.put("updateUser", userId);
				//点赞记录
				answersDao.createAnsPraise(rep);
				answersDao.addFeedbackReplyById(feedbackReplyId);
				jo.put("returnFlagCode", Constants.returnObj.returnPraise.code_1);
			}
			else
				//存在点赞记录
			{
				//取消点赞记录
				answersDao.delAnsPraise(feedbackId,feedbackReplyId, userId);
				answersDao.subFeedbackReplyById(feedbackReplyId);
				jo.put("returnFlagCode", Constants.returnObj.returnPraise.code_2);
			}
		}
		
		return "@"+jo.toString();
	}
	
	
	/**
	 * 查询问答列表
	 * @param start
	 * @param length
	 * @return
	 */
	@Get("getQueList")
	public String queryQueList(@Param("start") int start,@Param("length") int length) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> questionls = answersDao.query(start,length);
		
		List<Map> reps = returnQuestionsls(questionls);
		int size = answersDao.querySize();
		
		jo.put("questionls", reps);
		jo.put("total", size);
		return "@"+jo.toString();	
	}
	
	/**
	 * 问答下啦
	 * @param start
	 * @param length
	 * @return
	 */
	@Get("downList")
	public String queryPullList(@Param("createAt") String createAt,@Param("start") int start,@Param("length") int length) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> questionls = answersDao.queryPull(createAt,start,length);
		
		List<Map> reps = returnQuestionsls(questionls);
		
		for(Map rep:reps)
		{
			List<Map> answersls = answersDao.queryAnsById(Integer.parseInt(rep.get("id").toString()), 0, 3);
			//问答内容
			List<Map> answerReps = returnAnswersls(answersls);
			
			rep.put("answerReps", answerReps);
		}
		
		int size = answersDao.queryPullSize(createAt);
		
		jo.put("questionls", reps);
		jo.put("total", size);
		return "@"+jo.toString();
	}
	
	/**
	 * 问答上啦刷新
	 * @param start
	 * @param length
	 * @return
	 */
	@Get("upList")
	public String queryPushList(@Param("createAt") String createAt,@Param("start") int start,@Param("length") int length) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> questionls = answersDao.queryPush(createAt,start,length);
		
		List<Map> reps = returnQuestionsls(questionls);
		
		for(Map rep:reps)
		{
			List<Map> answersls = answersDao.queryAnsById(Integer.parseInt(rep.get("id").toString()), 0, 3);
			//问答内容
			List<Map> answerReps = returnAnswersls(answersls);
			
			rep.put("answerReps", answerReps);
		}
		
		int size = answersDao.queryPushSize(createAt);
		
		jo.put("questionls", reps);
		jo.put("total", size);
		return "@"+jo.toString();
	}
	
	/**
	 * 问答详情
	 * @param id
	 * @return
	 */
	@Get("getQueDetailById")
	public String queryQueDetailById(@Param("id") int id,@Param("devicesId") String devicesId) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		List<Map> questionls = answersDao.queryDetailById(id);
		//问答内容
		Map rep = returnQueObj(questionls.get(0));
		jo.put("question", rep);
		
		List<Map> answersls = answersDao.queryAnsById(id, 0, 10);
		//问答内容
		List<Map> answerReps = returnAnswersls(answersls);
		int answersSize = answersDao.queryAnsByIdSize(id);
		
		jo.put("answersls", answerReps);
		jo.put("total", answersSize);
		
		//添加问答的浏览量
		addFeedbackPVCount(id, devicesId);
		
		return "@"+jo.toString();	
	}
	
	/**
	 * 添加问答的浏览量
	 * @param newsId
	 * @param devicesId
	 */
	private void addFeedbackPVCount(int feedbackId,String devicesId)
	{
		//app用户信息by设备ID
		List<Map> apuser = appuserDao.queryAppUserByDevicesId(devicesId);
		if(apuser.size()>0)
		{
			//查询新闻By ID
			List<Map> anslis = answersDao.queryDetailById(feedbackId);
			if(anslis.size()>0)
			{
				int userId = Integer.parseInt(apuser.get(0).get("id").toString());
				int feedbackPvSize = answersDao.queryFeedbackPVSize(feedbackId, userId);
				if(feedbackPvSize==0)
				{
					Map rep = new HashMap();
					rep.put("feedbackId", feedbackId);
					rep.put("userId", userId);
					rep.put("userName", apuser.get(0).get("name")!=null?apuser.get(0).get("name").toString():"");
					rep.put("createUser", userId);
					rep.put("updateUser", userId);
					//创建新闻PV数
					answersDao.createFeedbackPV(rep);
					//增加PV量
					answersDao.addFeedbackPVById(feedbackId);
				}
			}
		}
	}
	
	/**
	 * 答详情Up
	 * @param id
	 * @param start
	 * @param length
	 * @param createAt
	 * @param order		0:id desc 1:praiseNum DESC
	 * @return
	 */
	@Get("getAnsDetailUpById")
	public String getAnsDetailUpById(@Param("id") int id,@Param("start") int start,@Param("length") int length,
			@Param("createAt") String createAt,@Param("order") int order) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> answersls = answersDao.queryAnsPushById(id, start, length,createAt,order);
		//问答内容
		List<Map> answerReps = returnAnswersls(answersls);
		int answersSize = answersDao.queryAnsPushByIdSize(id,createAt);
		
		jo.put("answersls", answerReps);
		jo.put("total", answersSize);
		return "@"+jo.toString();	
	}
	
	/**
	 * 答详情Down
	 * @param id
	 * @param start
	 * @param length
	 * @param createAt
	 * @param order		0:id desc 1:praiseNum DESC
	 * @return
	 */
	@Get("getAnsDetailDownById")
	public String getAnsDetailDownById(@Param("id") int id,@Param("start") int start,@Param("length") int length,
			@Param("createAt") String createAt,@Param("order") int order) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> answersls = answersDao.queryAnsPullById(id, start, length,createAt,order);
		//问答内容
		List<Map> answerReps = returnAnswersls(answersls);
		int answersSize = answersDao.queryAnsPullByIdSize(id,createAt);
		
		jo.put("answersls", answerReps);
		jo.put("total", answersSize);
		return "@"+jo.toString();	
	}
	
	/**
	 * 问答列表重构=》List<Map>
	 * @param answersls
	 * @return
	 */
	private List<Map> returnAnswersls(List<Map> answersls)
	{
		List<Map> reps = new ArrayList<Map>();
		for(Map rep :answersls)
		{
			Map obj = new HashMap();
			obj.put("id", rep.get("id"));
			
			List<Map> appuser = appuserDao.queryAppUserById(Integer.parseInt(rep.get("replyUserId").toString()));
			obj.put("replyUserId", rep.get("replyUserId"));
			obj.put("replyUserPhoto", appuser.get(0).get("photo"));
			obj.put("replyUserName", appuser.get(0).get("name"));
			
			
			obj.put("createAt", DateUtils.getBetweenMinNumber(rep.get("createAt").toString(),DateUtils.getNowTime()));//发布时间
			
			obj.put("reply", rep.get("reply"));
			obj.put("praiseNum", rep.get("praiseNum")==null?0:rep.get("praiseNum").toString());
			
			//int feedbackId,int feedbackReplyId,int userId
			int praisePoint = answersDao.queryAnsPraiseSize(Integer.parseInt(rep.get("feedbackId").toString()), 
					Integer.parseInt(rep.get("id").toString()), 
					Integer.parseInt(rep.get("replyUserId").toString()));
			
			//是否存在点赞
			obj.put("praiseOp", praisePoint);
			
			reps.add(obj);
		}
		
		return reps;
	}
	
	/**
	 * 重构问答详情
	 * @param rep
	 * @return
	 */
	private Map returnQueObj(Map rep)
	{
		Map obj = new HashMap();
		obj.put("id", rep.get("id"));
		List<Map> appuser = appuserDao.queryAppUserById(Integer.parseInt(rep.get("userId").toString()));
		obj.put("userId", rep.get("userId"));
		obj.put("userPhoto", appuser.get(0).get("photo"));
		obj.put("userName", appuser.get(0).get("name"));
		//缩率图
		String carouselImage = rep.get("carouselImage")==null?"":rep.get("carouselImage").toString();
		String[] imgLists=carouselImage.split(";");
		obj.put("carouselImages", imgLists);//缩率图
		obj.put("createAt", DateUtils.getMinusTime(rep.get("createAt").toString(), DateUtils.DATE_SMALL_STR, 0));//发布时间
		obj.put("msg", rep.get("msg"));
		obj.put("pvNum", rep.get("pvNum")==null?0:rep.get("pvNum").toString());
		obj.put("praiseNum", rep.get("praiseNum")==null?0:rep.get("praiseNum").toString());
		obj.put("commentsNum", rep.get("commentsNum")==null?0:rep.get("commentsNum").toString());
		obj.put("forwardNum", rep.get("forwardNum")==null?0:rep.get("forwardNum").toString());
		obj.put("collectNum", rep.get("collectNum")==null?0:rep.get("collectNum").toString());
		
		return obj;
	}
	
	/**
	 * 问答列表重构=》List<Map>
	 * @param answersls
	 * @return
	 */
	private List<Map> returnQuestionsls(List<Map> questionls)
	{
		List<Map> reps = new ArrayList<Map>();
		for(Map rep :questionls)
		{
			Map obj = new HashMap();
			obj.put("id", rep.get("id"));
			
			List<Map> appuser = appuserDao.queryAppUserById(Integer.parseInt(rep.get("userId").toString()));
			obj.put("userId", rep.get("userId"));
			obj.put("userPhoto", appuser.get(0).get("photo"));
			obj.put("userName", appuser.get(0).get("name"));
			
			//缩率图
			String carouselImage = rep.get("carouselImage")==null?"":rep.get("carouselImage").toString();
			String[] imgLists=carouselImage.split(";");
			obj.put("carouselImages", imgLists);//缩率图
			
			obj.put("createAt", DateUtils.getBetweenMinNumber(rep.get("createAt").toString(),DateUtils.getNowTime()));//发布时间
			
			obj.put("msg", rep.get("msg"));
			
			obj.put("pvNum", rep.get("pvNum")==null?0:rep.get("pvNum").toString());
			obj.put("praiseNum", rep.get("praiseNum")==null?0:rep.get("praiseNum").toString());
			obj.put("commentsNum", rep.get("commentsNum")==null?0:rep.get("commentsNum").toString());
			obj.put("forwardNum", rep.get("forwardNum")==null?0:rep.get("forwardNum").toString());
			obj.put("collectNum", rep.get("collectNum")==null?0:rep.get("collectNum").toString());
			
			reps.add(obj);
		}
		
		return reps;
	}
	
	/**
	 * 返回文字是否通过敏感词库
	 * @param contants
	 * @return	true:false
	 */
	private boolean returnWordFlag(String contants)
	{
		List<Map> words = configDao.queryLexiconAll();
		
		if(words.size()>0){
			for(Map rep:words){
				//查询敏感词
				String word = rep.get("name").toString();
				if(contants.indexOf(word)==-1){
					//判断不存在
					continue;
				}else{
					return true;
				}
			}
		}
		
		return false;
	}
}
